import { axios, api } from '@/Axios/index.js';
import _ from 'lodash';
import { DICT_CRM } from './DICT.js';

const KF = { 1: '普客客服', 2: '大客销售', 3: '大客客服' }

export default {
  namespaced: true,//postParams.js
  state: {
    //IM -- --
    numReadingType: {
      README: '已读未读状态',
      value: 0,
      DEFAULT: 0,
      options: [{ label: '全部', value: 0 }, { label: '未读', value: 1, }, { label: '已读', value: 2 }]
    },
    numReplyType: {
      README: '冒泡状态',
      value: 0,
      DEFAULT: 0,
      options: [{ label: '全部', value: 0 }, { label: '未冒泡', value: 1 }, { label: '冒泡', value: 2 }]
    },
    变量名_starType: {
      README: '星标改为标签的一种',
      value: 0,
      DEFAULT: 0,
      options: [{ label: 'red', value: 0 }, { label: 'yellow', value: 0 }, { label: 'blue', value: 0 }]
    },
    isNoReply: {
      README: '是否只要未回复',
      value: 0,
      DEFAULT: false,
      options: [{ label: '全部', value: false }, { label: '全部', value: true }]
    },
    strSearchName: {
      README: '按名字搜索，不搜索传空字符',
      value: '',
      DEFAULT: '',
      options: null
    },
    arrSelftag: {
      README: '按名字搜索，不搜索传空字符',
      value: [], unValue: [],//自设计用{pid,id}格式缓存备用，待取用时重新拼合sid
      DEFAULT: [], SPVALUE: 'sp',//用于selftag中，用来标记做反选使用的
      //搜索自用标签/反选自用标签
      //使用前端自定义的格式，但提交前拼成字符串（selfTagId用","分隔）给后端调用
    },
    变量名: {
      DEFAULT: 0, value: 0, README: '',
      options: [{ label: '', value: 0 }]
    },

    //IM --End--
    //CRM -- --
    RangeJoinTime: {
      DEFAULT: [], value: [], README: '进线时间（不搜索不传）',
    },
    RangeTradingMonth: {
      DEFAULT: [], value: [], README: '成交时间（精确到月）',
    },
    RangeAge: {
      DEFAULT: [], value: [], README: '年龄',
    },
    fromSources: {
      DEFAULT: 0, value: 0, README: '资源渠道（fromSourseId用","分隔）',
      options: [{ label: '', value: 0 }]//FROMSOURCES
    },
    isOverdue: {
      DEFAULT: true, value: true, README: '是否过期',
    },
    //CRM --End--
    DICT_IM_TAG: [],
    DICT_IM_TAG_2: [],
    DICT_CRM: DICT_CRM,
    FROMSOURCES: [
      // {fromSource_Id: 0,remark: "开发中",company_Department_Id: 0,code: "",department_Name: "",adChannel: "",isSyncToQywx: 0}
    ],//资源渠道
    crmProducts: [],//Crm产品列表
    imCfg: {
      // eSCompanyId: "",//微信平台ID，//转platform_app中获取
      // agentid: 0,//应用ID，//转platform_app中获取
      // departmentId: 0,//部门ID,//从来就没用过
    },

    crmCfg: {
      earlyWarningLevel: [],//预警标签组
      product: {//产品组 key:1=新单 2=续费 3=复购 value:产品ID
        searchType: 0,
        searchValues: {}
      },
      csTag: {//客服标签
        searchType: 0,
        searchValues: {}
      },
      csBelong: {//归属客服
        searchType: 0,
        searchValues: {}
      },
      character: {//性格
        searchType: 0,
        searchValues: {}
      },
      servicePreferences: {//服务喜好
        searchType: 0,
        searchValues: {}
      },
      operationalPreference: {//操作偏好
        searchType: 0,
        searchValues: {}
      }
    }
  },
  mutations: {
    const_im_tag: function (ctx, list) {
      list.forEach((v) => {
        ctx.DICT_IM_TAG.push({
          pid: v.id,
          pname: v.typeName,
          isMultiple: v.isMultiple,
          children: v.selfTag.map((s) => {
            return {
              pid: v.id,
              id: s.selfTagId,
              name: s.tagName,
              typeId: s.qywX_SelfTag_Type_Id,
            }
          })
        })
      })
      ctx.DICT_IM_TAG_2 = ctx.DICT_IM_TAG.reduce((t, p, i, a) => {
        return t.concat(p.children)
      }, []);//做个副本备用
    },
    const_fromSources: function (ctx, list) {
      list.forEach((v) => {
        ctx.FROMSOURCES.push({
          pid: v.company_Department_Id,
          pname: v.department_Name,
          id: v.fromSource_Id,
          name: v.remark,
          code: v.code,
          // v.adChannel
          // v.isSyncToQywx
        })
      })
    },
    const_crmProducts: function (ctx, list) {
      list.forEach((v) => {
        ctx.crmProducts.push({
          id: v.id,
          name: v.productName,
          timeSpan: v.timeSpan
        })
      })
    },
    setSelfTag: function (ctx, { pid, arr }) {
      let sp = ctx.SPVALUE;//特殊反选标记
      let isInvert = arr.includes(sp)
      let p = ctx.DICT_IM_TAG.find((v) => { return v.pid == pid });
      let c = _.get(p, 'children').map((v) => { return v.id });
      let c1 = isInvert ? [] : arr;//即将被选中的
      let c2 = isInvert ? c : [];//_.difference(c, c1)即将被反选中的
      console.log(ctx)
      return
      ctx.selftag[pid] = c1;
      ctx.unSelftag[pid] = c2;

    },
    setImcfgKeyValue: function (ctx, { key, value }) {
      if (!_.has(ctx, `imCfg.${key}`)) { return }
      //这里验证可能没什么意义，前面可以验证一下就算了，value就不验证了
      ctx.imCfg[key] = value;
    },
    setCRMcfgKeyValue: function (ctx, { key, value }) {
      console.log(key, value)
      if (!_.has(ctx, `crmCfg.${key}`)) { return }
      //这里验证可能没什么意义，前面可以验证一下就算了，value就不验证了
      ctx.crmCfg[key] = value;
    },
  },
  getters: {
    imTagId2obj: function (ctx) {
      return function (id) {
        let pid = ctx.DICT_IM_TAG_2.find((v) => { return v.id === id }).pid
        let p = ctx.DICT_IM_TAG.find((v) => { return v.pid == pid });
        let c = p.children.find((v) => { return v.id == id });
        return c
      }
    },//用id来检索标签对象
    getSelfTag: function (ctx) {
      return function () {
        let selftag = [];
        let unSelftag = [];
        _.forIn(ctx.selftag, (v, k) => { selftag.push(v) })
        _.forIn(ctx.unSelftag, (v, k) => { unSelftag.push(v) })
        return {
          selftag: _.flatten(selftag).join(','),
          unSelftag: _.flatten(unSelftag).join(','),
        }
      }
    },//提交请求参数的一部分
    get_im_cfg: function (ctx) {
      return function () {
        return {
          // departmentId//无用占位，对位文档
          readingType: ctx.imCfg.readingType,
          replyType: ctx.imCfg.replyType,
          // isStar: ctx.imCfg.isStar,//星标改了
          isNoReply: ctx.imCfg.isNoReply,
          searchName: ctx.imCfg.searchName,
        }
      };
    },//还不需要复杂操作的imcfg属性获取留给这里整合
    get_crm_cfg: function (ctx) {
      return function () {
        return ctx.crmCfg;
      }
    },//还不需要复杂操作的crmcfg属性获取留给这里整合
  },
  actions: {
    init_DICT_IM_TAG: function (ctx) {
      return axios.get('/api/ChatMsg/GetSelfTags').then((res) => {
        if (res.code === 200) {
          console.log('%c [ res.data ]-221', 'font-size:13px; background:pink; color:#bf2c9f;', res.data)
          ctx.commit('const_im_tag', res.data)
          return Promise.resolve(200)
        }
      })
    },
    init_FROMSOURCES: function (ctx, { ceid: ceid }) {
      return axios.get('/api/ChatMsg/GetFromSources', {
        params: { companyEmployeeId: ceid }
      }).then((res) => {
        if (res.data.length <= 0) {
          return Promise.reject('IM资源渠道，没有数据返回')
        }
        if (res.code === 200) {
          ctx.commit('const_fromSources', res.data)
          return Promise.resolve(200)
        }
      })
    },
    init_crmProducts: function (ctx) {
      return axios.get('/api/ImCrm/GetCrmProducts').then((res) => {
        if (res.data.length <= 0) {
          return Promise.reject('Crm产品列表，没有数据返回')
        }
        if (res.code === 200) {
          ctx.commit('const_crmProducts', res.data)
          return Promise.resolve(200)
        }
      })
    }
  },
}